// Copyright (C) 2024 Kumo inc.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <ktest/ktest.h>
#include <turbo/times/time.h>
#include <turbo/base/macros.h>
#include <turbo/log/logging.h>
#include <kthread/internal/task_group.h>
#include <kthread/internal/kthread.h>

namespace {
    void *sleeper(void *arg) {
        kthread_usleep((long) arg);
        return nullptr;
    }

    TEST(ListTest, join_thread_by_list) {
        kthread_list_t list;
        ASSERT_EQ(0, kthread_list_init(&list, 0, 0));
        std::vector<kthread_t> tids;
        for (size_t i = 0; i < 10; ++i) {
            kthread_t th;
            ASSERT_EQ(0, kthread_start_urgent(
                    &th, nullptr, sleeper, (void *) 10000/*10ms*/));
            ASSERT_EQ(0, kthread_list_add(&list, th));
            tids.push_back(th);
        }
        ASSERT_EQ(0, kthread_list_join(&list));
        for (size_t i = 0; i < tids.size(); ++i) {
            ASSERT_FALSE(kthread::TaskGroup::exists(tids[i]));
        }
        kthread_list_destroy(&list);
    }

    TEST(ListTest, join_a_destroyed_list) {
        kthread_list_t list;
        ASSERT_EQ(0, kthread_list_init(&list, 0, 0));
        kthread_t th;
        ASSERT_EQ(0, kthread_start_urgent(
                &th, nullptr, sleeper, (void *) 10000/*10ms*/));
        ASSERT_EQ(0, kthread_list_add(&list, th));
        ASSERT_EQ(0, kthread_list_join(&list));
        kthread_list_destroy(&list);
        ASSERT_EQ(EINVAL, kthread_list_join(&list));
    }
} // namespace
